import Vue from "vue";
import Vuex, { mapState } from "vuex";
import axios from "axios"; //引用 axios

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    //存放用户登录的参数
    token: "",
    name: "",
    //存放数据
    data: {},
    error: {},
  },

  mutations: {
    /**
     * 存放用户登录状态
     */
    login(state, usertoken) {
      localStorage.setItem("usertoken", usertoken);
      state.token = usertoken;
    },

    /**
     * 清楚用户登录状态
     */
    logout(state) {
      localStorage.removeItem("usertoken");
      localStorage.removeItem("userName");
      state.token = "";
      state.name = "";
    },

    /**
     * 读取缓存中的用户数据
     *
     */
    loadToken(state) {
      if (state.token === "") {
        state.token = localStorage.getItem("usertoken");
        state.name = localStorage.getItem("userName");
      }
    },

    /**
     * 存放用户姓名
     */
    userName(state, name) {
      localStorage.setItem("userName", name);
      state.name = name;
    },
  },

  actions:{

    request(context,obj){
      if(obj.style == 'get'){
        
        axios.get(obj.url,{params:obj.params}).then(res => {
          if(res.status == 200){
            
            var data = res.data.docs
            context.state.data[obj.name] = data;
          }
      })
      .catch(error => {console.log(error)})
      }
      
     else if(obj.style === 'post'){
      axios.post(obj.url,obj.param).then(res =>{
        if(res.status == 200){
            context.commit('saveData',obj.name,res.data);
          }
        }).catch(error => {console.log(error)})
     }
     else if(obj.style === 'put'){
      axios.put(obj.url,obj.param).then(res =>{
        if(res.status == 200){
            context.commit('saveData',obj.name,res.data);
          }
       }).catch(error => {console.log(error)})
     }
    },


    all(context,requests,name){
      axios.all(requests).then(res =>{
        if (res.every(function(){
          return res.status == 200;
        })) {
          context.commit('saveData',name,res.data);
        }
      })
    }

      
  }
});